import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast
} from "../../utils/asyncWX.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: {},
    cart: [],
    allChecked: false,
    totalPrice: 0,
    totalNum: 0
  },
  onShow() {
    const address = wx.getStorageSync("address");
    const cart = wx.getStorageSync("cart") || [];
    // const allChecked=cart.length?cart.every(val=>val.checked):false;
    this.setData({
      address
    })
    this.setCart(cart);
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  async handleChooseAddress() { //点击获取收货地址事件
    /* wx.getSetting({
      success: (result) => {
        console.log(result);
        const scopeAddress = result.authSetting["scope.address"];
        if (scopeAddress || scopeAddress === undefined) {
          wx.chooseAddress({
            success: (res) => {
              console.log(res);
            }
          });
        } else {
          wx.openSetting({
            success: (result) => {
              wx.chooseAddress({
                success: (res) => {
                  console.log(res);
                }
              });
            }
          });
        }
      }
    }); */
    try {
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      if (!scopeAddress) {
        await openSetting();
      }
      let address = await chooseAddress();
      address.detailAddress = address.provinceName + address.cityName + address.countyName + address.detailInfo;
      wx.setStorageSync("address", address);
    } catch (err) {
      console.log(err);
    }
  },
  handleItemChange(e) {
    console.log(e.currentTarget.dataset.id);
    const goods_id = e.currentTarget.dataset.id;
    let cart = this.data.cart;
    let index = cart.findIndex((val, index) => val.goods_id === goods_id);
    cart[index].checked = !cart[index].checked;
    this.setCart(cart);
  },
  //设置购物车状态，同时计算底部工具栏的数据，全选、总价格、购买数量
  setCart(cart) {
    let allChecked = true;
    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach((val, index) => {
      if (val.checked) {
        totalPrice += val.goods_price * val.num;
        totalNum += val.num;
      } else {
        allChecked = false
      }
    });
    allChecked = cart.length != 0 ? allChecked : false;
    this.setData({
      cart,
      allChecked,
      totalPrice,
      totalNum
    })
    wx.setStorageSync("cart", cart);
  },
  handleItemAllCheck() {
    let cart = this.data.cart;
    let allChecked = this.data.allChecked;
    allChecked = !allChecked;
    cart.forEach(val => val.checked = allChecked);
    this.setCart(cart);
  },
  async handleItemNumEdit(e) {
    console.log(e.currentTarget.dataset.id);
    console.log(e.currentTarget.dataset.operation);
    const id = e.currentTarget.dataset.id;
    const operation = e.currentTarget.dataset.operation;
    let cart = this.data.cart;
    let index = cart.findIndex(val => val.goods_id === id);
    if (cart[index].num === 1 && operation === -1) {
      const res = await showModal({
        content: "您是否要删除?"
      });
      if (res.confirm) {
        cart.splice(index, 1);
        this.setCart(cart);
      } else if (res.cancel) {
        console.log("用户取消删除!");
      }
    } else {
      cart[index].num += operation;
      this.setCart(cart);
    }
  },
  async handlePay() {
    const address = this.data.address;
    const totalNum = this.data.totalNum;
    if (!address.userName) {
      await showToast({
        title: "您还没有选择收货地址!"
      })
      return;
    }
    if (totalNum == 0) {
      await showToast({
        title: "您还没有选购商品!"
      })
      return;
    }
    wx.navigateTo({
      url: '/pages/pay/index'
    });
  }
})